import 'package:flutter/material.dart';

enum SelectionMode { single, multiple }

class SelectableListDialog<T> extends StatefulWidget {
  final String title;
  final List<T> items;
  final List<T> selectedItems;
  final SelectionMode selectionMode;
  final Function(List<T>) onConfirmed;
  final String Function(T) itemBuilder; // 新增：用于构建显示文本
  final bool Function(T, T)? itemCompare; // 新增：用于比较两个对象是否相同
  final VoidCallback? onCancel; // 新增：取消回调

  const SelectableListDialog({
    Key? key,
    required this.title,
    required this.items,
    this.selectedItems = const [],
    this.selectionMode = SelectionMode.single,
    required this.onConfirmed,
    required this.itemBuilder,
    this.itemCompare,
    this.onCancel, // 新增参数
  }) : super(key: key);

  @override
  State<SelectableListDialog<T>> createState() => _SelectableListDialogState<T>();
}

class _SelectableListDialogState<T> extends State<SelectableListDialog<T>> {
  late List<T> _selectedItems;

  @override
  void initState() {
    super.initState();
    _selectedItems = List<T>.from(widget.selectedItems);
  }

  bool _isSelected(T item) {
    for (final selectedItem in _selectedItems) {
      if (widget.itemCompare != null) {
        if (widget.itemCompare!(selectedItem, item)) {
          return true;
        }
      } else {
        if (selectedItem == item) {
          return true;
        }
      }
    }
    return false;
  }

  void _toggleSelection(T item) {
    setState(() {
      if (widget.selectionMode == SelectionMode.single) {
        _selectedItems.clear();
        _selectedItems.add(item);
      } else {
        bool found = false;
        int index = -1;

        // 查找是否已选中
        for (int i = 0; i < _selectedItems.length; i++) {
          if (widget.itemCompare != null) {
            if (widget.itemCompare!(_selectedItems[i], item)) {
              found = true;
              index = i;
              break;
            }
          } else {
            if (_selectedItems[i] == item) {
              found = true;
              index = i;
              break;
            }
          }
        }

        if (found) {
          _selectedItems.removeAt(index);
        } else {
          _selectedItems.add(item);
        }
      }
    });
  }

  void _toggleSelectAll() {
    setState(() {
      if (_selectedItems.length == widget.items.length) {
        // 全部选中时点击 -> 取消全选
        _selectedItems.clear();
      } else {
        // 部分或未选中时点击 -> 全选
        _selectedItems = List<T>.from(widget.items);
      }
    });
  }

  // 处理取消操作
  void _handleCancel() {
    if (widget.onCancel != null) {
      widget.onCancel!(); // 调用自定义取消回调
    } else {
      // 默认行为：尝试pop，如果失败则不执行任何操作
      Navigator.maybePop(context);
      // Navigator.of(context).pop();
    }
  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return AlertDialog(
      title: Row(
        children: [
          Expanded(child: Text(widget.title)),
          if (widget.selectionMode == SelectionMode.multiple)
            TextButton(
              onPressed: _toggleSelectAll,
              child: Text(
                _selectedItems.length == widget.items.length ? '取消全选' : '全选',
              ),
            ),
        ],
      ),
      content: SizedBox(
        width: screenSize.width * 0.6,
        height: screenSize.height * 0.55,
        child: GridView.builder(
          gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
            maxCrossAxisExtent: 100, // 每个item最大宽度100
            mainAxisSpacing: 10, // 垂直间距
            crossAxisSpacing: 10, // 水平间距
            childAspectRatio: 2.5, // 宽高比 = width/height = 100/40 = 2.5
          ),
          itemCount: widget.items.length,
          itemBuilder: (context, index) {
            final item = widget.items[index];
            final isSelected = _isSelected(item);
            return InkWell(
              onTap: () => _toggleSelection(item),
              child: Container(
                decoration: BoxDecoration(
                  color: isSelected ? const Color(0xFF13345F) : const Color(0xFFF2F4F8),
                  borderRadius: BorderRadius.circular(3),
                ),
                child: Center(
                  child: Text(
                    widget.itemBuilder(item),
                    textAlign: TextAlign.center,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      color: isSelected ? Colors.white : const Color(0xFF222222),
                      fontSize: 15,
                    ),
                  ),
                ),
              ),
            );
          },
        ),
      ),
      actions: [
        TextButton(
          onPressed: _handleCancel, // 使用新的取消处理方法
          child: const Text('取消'),
        ),
        ElevatedButton(
          onPressed: () => widget.onConfirmed(_selectedItems),
          child: const Text('确认'),
        ),
      ],
    );
  }
}
